import { constantRoutes } from '@/router';
import { getRouters } from '@/api/login';
import { filterAsyncRouter } from "@/utils/routerUtil";

const permission = {
  state: {
    routes: [],
    addRoutes: [],
    sidebarRouters: [],
    externalSystem: []
  },
  mutations: {
    SET_ROUTES: (state, routes) => {
      state.addRoutes = routes;
      state.routes = constantRoutes.concat(routes);
    },
    SET_SIDEBAR_ROUTERS: (state, routers) => {
      state.sidebarRouters = constantRoutes.concat(routers);
    },
  },
  actions: {
    // 生成路由
    GenerateRoutes({ commit }) {
      return new Promise(resolve => {
        // 向后端请求路由数据
        getRouters().then(res => {
          const sdata = JSON.parse(JSON.stringify(res));
          const rdata = JSON.parse(JSON.stringify(res));
          const sidebarRoutes = filterAsyncRouter(sdata);
          const rewriteRoutes = filterAsyncRouter(rdata, true);
          rewriteRoutes.push({ path: '*', redirect: '/404', hidden: true });
          commit('SET_ROUTES', rewriteRoutes);
          commit('SET_SIDEBAR_ROUTERS', sidebarRoutes);
          resolve(rewriteRoutes);
        })
      })
    }
  }
}

export default permission;
